
// arduino script for singlee MMG input, focusing on the RMSing of values every 
// 100 or so samples.
// Written by Edward Brial 

#include <Wire.h>
#include <math.h>
#include "filter.h"

#define RMSsize 150      // Sample size of RMS window, up here so it's easy to change

//call prototypes & global variables
//int RMSfun (short* readings, int length);
unsigned long lastmeasure;
int RMSfinal;
short tempread[RMSsize];
short filtarray[RMSsize];

char address;

void setup(){
  pinMode(10,INPUT); //pin 10 used to set address, 1 for 0x02, 0 for 0x01 
  address=digitalRead(10)+1;//0x02 if pin 10 is high, 0x01 if pin 10 is low
  Wire.begin(address);
  Wire.onRequest(sendRMS);
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop(){
  int i;

  for (i=0 ; i < RMSsize; i++ ) { //i++ = unit increment every loop
    lastmeasure = micros(); // starts lastmeasure from micros current timing point
    tempread[i] = analogRead(A3);
    while (micros() < lastmeasure + 1250) ; // waits for 1250microsecs before next reading
  }
  filter(tempread, filtarray, RMSsize); //Data array will be filtered
  RMSfinal = RMSfun(filtarray, RMSsize);   //RMS value of Data Array
}

// I2C subroutine
void sendRMS (void) {
  Wire.write((byte*)(&RMSfinal),2);
}

// function to be written to take the moving rms of each temp sample.
int RMSfun (short* readings, int length){
  int j;
  int Sum = 0;
  int RmsVal;

  for (j=0 ; j < length; j++) {
    readings[j] = readings[j]*readings[j]; //squares all the individual values. rms = sqrt(1/n(sum(xi^2)))
    Sum = Sum + readings[j];
  }
  RmsVal = sqrt(Sum/length);

  return RmsVal;
}






